package com.example.lexiangbackend.service;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpHeaders;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UrlMusicService {

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 验证外部音乐URL是否有效
     */
    public boolean validateMusicUrl(String url) {
        try {
            if (url == null || url.isEmpty()) {
                return false;
            }

            // 检查URL格式
            URL musicUrl = new URL(url);
            
            // 支持的音乐域名白名单
            String host = musicUrl.getHost().toLowerCase();
            if (isSupportedMusicDomain(host)) {
                // 对于支持的音乐平台，直接返回true
                return true;
            }

            // 对于其他URL，尝试检查是否为音频文件
            URLConnection connection = musicUrl.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            
            String contentType = connection.getContentType();
            if (contentType != null && contentType.startsWith("audio/")) {
                return true;
            }

            // 检查URL扩展名
            String path = musicUrl.getPath().toLowerCase();
            return path.endsWith(".mp3") || path.endsWith(".wav") || 
                   path.endsWith(".flac") || path.endsWith(".m4a") ||
                   path.endsWith(".aac") || path.endsWith(".ogg");

        } catch (Exception e) {
            System.err.println("验证URL失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 检查是否为支持的音乐平台域名
     */
    private boolean isSupportedMusicDomain(String host) {
        return host.contains("music.163.com") ||  // 网易云音乐
               host.contains("y.qq.com") ||       // QQ音乐
               host.contains("xiami.com") ||      // 虾米音乐
               host.contains("kugou.com") ||      // 酷狗音乐
               host.contains("kuwo.cn") ||        // 酷我音乐
               host.contains("soundcloud.com") || // SoundCloud
               host.contains("spotify.com");      // Spotify
    }

    /**
     * 从网易云音乐URL中提取歌曲ID
     */
    public String extractSongIdFromNeteaseUrl(String url) {
        try {
            // 匹配网易云音乐URL中的歌曲ID
            Pattern pattern = Pattern.compile("id=(\\d+)");
            Matcher matcher = pattern.matcher(url);
            if (matcher.find()) {
                return matcher.group(1);
            }
        } catch (Exception e) {
            System.err.println("提取网易云音乐ID失败: " + e.getMessage());
        }
        return null;
    }

    /**
     * 获取音乐的元数据信息（如时长等）
     */
    public MusicMetadata getMusicMetadata(String url) {
        try {
            if (url.contains("music.163.com")) {
                return getNeteaseMetadata(url);
            }
            
            // 对于其他URL，返回基本信息
            return new MusicMetadata(url, 0, null, null);
            
        } catch (Exception e) {
            System.err.println("获取音乐元数据失败: " + e.getMessage());
            return new MusicMetadata(url, 0, null, null);
        }
    }

    /**
     * 获取网易云音乐的元数据
     */
    private MusicMetadata getNeteaseMetadata(String url) {
        String songId = extractSongIdFromNeteaseUrl(url);
        if (songId == null) {
            return new MusicMetadata(url, 0, null, null);
        }

        try {
            // 这里可以调用网易云音乐的API获取详细信息
            // 由于API限制，暂时返回基本信息
            return new MusicMetadata(url, 240, null, null); // 默认240秒
        } catch (Exception e) {
            return new MusicMetadata(url, 0, null, null);
        }
    }

    /**
     * 音乐元数据内部类
     */
    public static class MusicMetadata {
        private final String url;
        private final int duration;
        private final String title;
        private final String artist;

        public MusicMetadata(String url, int duration, String title, String artist) {
            this.url = url;
            this.duration = duration;
            this.title = title;
            this.artist = artist;
        }

        public String getUrl() {
            return url;
        }

        public int getDuration() {
            return duration;
        }

        public String getTitle() {
            return title;
        }

        public String getArtist() {
            return artist;
        }
    }

    /**
     * 处理外部URL，返回可用的音乐URL
     */
    public String processExternalUrl(String externalUrl) {
        if (externalUrl == null || externalUrl.isEmpty()) {
            throw new RuntimeException("外部URL不能为空");
        }

        if (!validateMusicUrl(externalUrl)) {
            throw new RuntimeException("无效的音乐URL");
        }

        // 对于网易云音乐等平台，直接返回原URL
        // 在实际播放时，前端会处理跨域问题
        return externalUrl;
    }
} 